package com.zy.system.utils;

import com.zy.model.system.SysMenu;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author Gong
 * @Description
 * @dATE 2023/6/9 9:36
 **/
public class MenuHelper {
    /**
     * 使用递归方法建菜单
     * @param sysMenuList
     * @return
     */
    public static List<SysMenu> buildTree(List<SysMenu> sysMenuList) {
        List<SysMenu> trees = new ArrayList<>();
        for (SysMenu sysMenu : sysMenuList) {
            if (sysMenu.getParentId().longValue() == 0) {
                trees.add(findChildren(sysMenu,sysMenuList));
            }
        }
        return trees;
    }
    //从根节点进行递归查询，判断id=parentid是否相同，如果相同进行子节点封装，否则不封装
    private static SysMenu findChildren(SysMenu sysMenu, List<SysMenu> sysMenuList) {
        sysMenu.setChildren(new ArrayList<SysMenu>());

        for (SysMenu it : sysMenuList) {
            if(sysMenu.getId().equals(it.getParentId() ==null ? 0+"" : it.getParentId().toString())) {
                if (sysMenu.getChildren() == null) {
                    sysMenu.setChildren(new ArrayList<>());
                }
                sysMenu.getChildren().add(findChildren(it,sysMenuList));
            }
        }
        return sysMenu;
    }
}
